import {router,handleRoutes} from "@/router";
import {getToken} from "@/utils/auth";
import useUserStore from "@/store/modules/user";
import {hideProgress, showProgress} from "@/utils/utils";
import usePermissionStore from "@/store/modules/permission";

// 全局前置守卫
let isLoadInfo = false
router.beforeEach(async (to, from, next) => {
    showProgress();
    const token = getToken();
    const userStore = useUserStore()
    const permissionStore = usePermissionStore();

    // 若未登录强制登录
    if (!token && to.path !== '/login') {
        isLoadInfo = false;
        return next({path:'/login'});
    }

    // 若已登录 若to是登录则强制首页
    if (token && to.path === '/login') {
        isLoadInfo = false;
        return next({ path:from.path ? from.path : "/" })
    }


    let isNew = false;
    // 若已登录 获取用户信息
    if (token && (!isLoadInfo || userStore.needRefreshInfo)) {
        const {menus,roleNames} = await userStore.getInfo()
        permissionStore.setMenus(menus)
        permissionStore.setRoleNames(roleNames)
        isNew = handleRoutes(menus);
        isLoadInfo = true
    }

    // 设置页面标题
    document.title = to.meta.title || ''
    isNew ? next(to.fullPath) : next()
})

// 全局后置守卫
router.afterEach((to, from) => {
    hideProgress()
})
